<?php
/**
 * Bootstrap.php
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@mygem.org so we can send you a copy immediately.
 *
 * @copyright   Copyright (c) 2012, MyGem <info@mygem.org>
 * @package     MyGem
 */


set_time_limit(0);
function __autoload($className) {
    MyGem_Bootstrap::autoload($className);
}

class MyGem_Bootstrap
{

    protected static $_instance = NULL;
    protected $_paths = array();

    public static function getInstance()
    {
        if (self::$_instance === NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function autoload($className)
    {
        include str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    }

    protected function _setupPaths($webRoot)
    {
        $webRoot = realpath($webRoot);
        $this->_paths['mygem'] = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..');
        $this->_paths['webroot'] = $webRoot;
        $app = $webRoot . DIRECTORY_SEPARATOR . 'app';
        $this->_paths['config'] = $app . DIRECTORY_SEPARATOR . 'config';
        $this->_paths['models'] = $app . DIRECTORY_SEPARATOR . 'models';
        $this->_paths['controllers'] = $app . DIRECTORY_SEPARATOR . 'controllers';
        $this->_paths['views'] = $app . DIRECTORY_SEPARATOR . 'views';
        set_include_path(implode(PATH_SEPARATOR, $this->_paths) . PATH_SEPARATOR . get_include_path());
        return $this;
    }

    public function run($webRoot = NULL)
    {
        if ($webRoot === NULL) {
            $webRoot = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..');
        }
        $this->_setupPaths($webRoot);

        $controller = 'index'; // default controller
        $action = 'index'; // default action
        $queries = array(
            'c'=>$controller,
            'a'=>$action,
        );
        if (strlen($_SERVER['QUERY_STRING']) > 0) {
            parse_str($_SERVER['QUERY_STRING'], $queries);
            if (array_key_exists('c', $queries)) {
                $controller = $queries['c'];
            }
            if (array_key_exists('a', $queries)) {
                $action = $queries['a'];
            }
        }

        $controller = str_replace('-',' ',strtolower($controller));
        $controller = ucwords($controller);
        $controller = str_replace(' ','',$controller) . 'Controller';
        $fileController = $this->_paths['controllers'] . DIRECTORY_SEPARATOR . "{$controller}.php";
        if (!file_exists($fileController)) {
            throw new MyGem_Exception("Controller '{$controller}' could not found");
        }
        require_once $fileController;

        $objController = new $controller();
        $objController->setRequestQueries($queries);
        $objController->setPaths($this->_paths);

        $action = str_replace('-',' ',strtolower($action));
        $action = ucwords($action);
        $action = str_replace(' ','',$action);
        $action = strtolower(substr($action,0,1)) . substr($action,1);
        $objController->setAction($action);
        $objController->setupConfig();
        $objController->init();

        $method = $objController->getAction().'Action';
        if (!method_exists($objController, $method)) {
            $method = 'errorAction';
        }

        unset($queries['c']);
        unset($queries['a']);
        call_user_func_array(array($objController,$method), $queries);
        if (!$objController->isViewRendered()) $objController->render();
    }

}

